package com.atguigu.common.util;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvReader;
import com.atguigu.common.base.entity.TimestampBase;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CsvHelper {
    private final CsvReadConfig config = new CsvReadConfig().setFieldSeparator('\t').setContainsHeader(true).setHeaderLineNo(0L).setBeginLineNo(0L);

    public <T extends TimestampBase> List<T> csvToEntities(LocalDateTime time, String csvPath, Class<T> entityClass) {
        BufferedReader reader = ResourceUtil.getUtf8Reader(csvPath);
        return new CsvReader(reader, config).stream().map(c -> {
            T bean = c.toBean(entityClass);
            bean.setCreateTime(time);
            bean.setUpdateTime(time);
            return bean;
        }).collect(Collectors.toList());
    }
}
